package com.filter;

import com.entry.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * --- Be Humble and Hungry ---
 *
 * @author McMeloxD
 * @date 2024/6/27
 * @desc
 */
@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;
        String uri = req.getRequestURI( );
        System.out.println(uri);
        // 如果是静态资源/登录相关就放行
        if (uri.contains("css") || uri.contains("*js") || uri.contains("ico") ||uri.contains("jpg") || uri.contains("png")
                 || uri.contains("login") || uri.contains("logout")|| uri.contains("reg")) {
            System.out.println("静态放行放行");
            // 放行
            chain.doFilter(request,response);

        } else { // 其他资源就拦截开始过滤
            System.out.println("拦截进行判断");
            HttpSession session = req.getSession( );
            User user = (User) session.getAttribute("user");
            System.out.println(user);
            if (user != null) {
                // 放行
                System.out.println("拦截后发现有登录放行");
                chain.doFilter(request,response);

            } else {
                // 说明之前没有登录,跳转首页 不放行
                System.out.println("拦截后发现没登录，不放行跳转登录");
                resp.sendRedirect("/login.jsp");
            }
        }
    }

    @Override
    public void destroy() {

    }
}
